package _05_二叉树;

import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/
 */
public class _114_二叉树展开为链表 {

    // 递归
    public void flatten2(TreeNode root) {
        if (root == null) return;
        // 改变链表结构
        flatten2(root.left);
        flatten2(root.right);

        TreeNode temp = root.right;
        root.right = root.left;
        root.left = null;
        for (;;) {
            if (root.right != null) {
                root = root.right;
            } else {
                root.right = temp;
                root.left = null;
                break;
            }
        }
    }


    public void flatten(TreeNode root) {
        if (root == null) return;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        TreeNode prev = null;
        while (!stack.isEmpty()) {
            TreeNode node = stack.peek();

            if (node.right == null && node.left == null || (prev != null && (node.left == prev || node.right == prev))) {
                node = stack.pop();
                // 遍历根节点
                prev = node;

                // 设置节点
                TreeNode temp = node.right;
                node.right = node.left;
                node.left = null;
                for (;;) {
                    if (node.right != null) {
                        node = node.right;
                    } else {
                        node.right = temp;
                        node.left = null;
                        break;
                    }
                }
            } else {
                if (node.right != null) stack.push(node.right);

                if (node.left != null) stack.push(node.left);
            }
        }
    }
}
